package com.ruoyi.project.shortUrl.url.controller;

import java.text.ParseException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.shortUrl.config.service.ShortConfigService;
import com.ruoyi.project.shortUrl.url.domain.DomainOfShortUrl;
import com.ruoyi.project.shortUrl.url.domain.ShortUrl;
import com.ruoyi.project.shortUrl.url.service.IDomainOfShortUrlService;
import com.ruoyi.project.shortUrl.url.service.IShortUrlService;
import com.ruoyi.project.shortUrl.util.ShortUrlRoleKey;
import com.ruoyi.project.system.user.domain.User;

/**
 * 短链接Controller
 * 
 * @author ruoyi
 * @date 2020-03-29
 */
@Controller
@RequestMapping("/short/url")
public class ShortUrlController extends BaseController
{
    private String prefix = "shortUrl/url";

    @Autowired
    private IShortUrlService shortUrlService;
    
    @Autowired
    private ShortConfigService shortConfigService;
    
    @Autowired
    private IDomainOfShortUrlService domainService;
    
    @RequiresPermissions("short:url:view")
    @GetMapping()
    public String url()
    {
        return prefix + "/url";
    }

    /**
     * 查询短链接列表
     */
    @RequiresPermissions("short:url:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ShortUrl shortUrl)
    {
    	User u = ShiroUtils.getSysUser();
    	if(!u.isAdmin()) {
    		shortUrl.setCreateUserId(u.getUserId().toString());
    	}
    	
        startPage();
        List<ShortUrl> list = shortUrlService.selectShortUrlList(shortUrl);
        return getDataTable(list);
    }

    /**
     * 导出短链接列表
     */
    @RequiresPermissions("short:url:export")
    @Log(title = "短链接", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ShortUrl shortUrl)
    {
        List<ShortUrl> list = shortUrlService.selectShortUrlList(shortUrl);
        ExcelUtil<ShortUrl> util = new ExcelUtil<ShortUrl>(ShortUrl.class);
        return util.exportExcel(list, "url");
    }

    /**
     * 新增短链接
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
    	//注册用户
    	User u = ShiroUtils.getSysUser();
    	//注册用户不是管理员
    	if(ShortUrlRoleKey.REGISTER.equals(u.getShortUserType())) {
    		int expireDay = shortConfigService.getREGISTER_DEFAULT_SHORT_EXPIRE_TIME();
    		mmap.put("expireDay", expireDay);
    	}
		
        return prefix + "/add";
    }

    /**
     * 新增保存短链接
     */
    @RequiresPermissions("short:url:add")
    @Log(title = "短链接", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ShortUrl shortUrl)
    {
    	User u = ShiroUtils.getSysUser();
    	int expireDay = -1;
    	try {
    		expireDay = Integer.parseInt(shortUrl.getExpirationTime());
		} catch (Exception e) {
			expireDay = -1;
		}
    	
        return toAjax(shortUrlService.createShortUrl(u.getShortUserType(), shortUrl, expireDay));
    }

    /**
     * 修改短链接
     */
    @GetMapping("/edit/{shortCode}")
    public String edit(@PathVariable("shortCode") String shortCode, ModelMap mmap)
    {
        ShortUrl shortUrl = shortUrlService.selectShortUrlById(shortCode);
        mmap.put("shortUrl", shortUrl);
        
        List<DomainOfShortUrl> otherDomains = domainService.selectList(null);
        for(DomainOfShortUrl o:otherDomains) {
        	if(o.getDomain().equals(shortUrl.getMainDomain())) {
        		otherDomains.remove(o);
        		break;
        	}
        }
    	mmap.put("otherDomains", otherDomains);
    	
    	//注册用户不是管理员
    	User u = ShiroUtils.getSysUser();
    	if(!u.isAdmin()) {
    		mmap.put("isAdmin", false);
    	}else {
    		mmap.put("isAdmin", true);
    	}
    	
    	if(StringUtils.isBlank(shortUrl.getExpirationTime())) {
			mmap.put("expireDay", -1);
		}else {
			int expireDay = -1;
			try {
				expireDay = DateUtils.getDayDiffer(DateUtils.getNowDate(), DateUtils.parseDate(shortUrl.getExpirationTime(), DateUtils.YYYY_MM_DD));
			} catch (ParseException e) {
				expireDay = -1;
			}
			mmap.put("expireDay", expireDay);
		}
    	
        return prefix + "/edit";
    }

    /**
     * 修改保存短链接
     */
    @RequiresPermissions("short:url:edit")
    @Log(title = "短链接", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ShortUrl shortUrl)
    {
    	User u = ShiroUtils.getSysUser();
    	Integer expireDay = null;
    	if(ShortUrlRoleKey.ADMIN.equals(u.getShortUserType())) {
    		expireDay = Integer.parseInt(shortUrl.getExpirationTime());
    	}
        return toAjax(shortUrlService.editShortUrl(u, shortUrl.getShortCode(), shortUrl.getTargetUrl(), expireDay));
    }

    /**
     * 删除短链接
     */
    @RequiresPermissions("short:url:remove")
    @Log(title = "短链接", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(shortUrlService.deleteShortUrlByIds(ids));
    }
    
}
